//
//  ViewController.m
//  ZAKER
//
//  Created by Anyfish002 on 16/2/1.
//  Copyright © 2016年 yaohongchao. All rights reserved.
//

#import "ViewController.h"
#import "AFNetworking.h"
#import "ZKModel.h"
#import "MJExtension.h"
#import "SDWebImageDownloader.h"
#import "SDImageCache.h"
#import "SDWebImageManager.h"

@interface ViewController ()<UIWebViewDelegate>
@property(nonatomic,weak)UIWebView *webView;
@property(nonatomic,strong)ZKModel *zkModel;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setui];
    [self setData];
    // Do any additional setup after loading the view.
}

-(void)setui{
    UIWebView *webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
    webView.delegate=self;
    [self.view addSubview:webView];
    self.webView=webView;
}

-(void)setData{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:@"http://iphone.myzaker.com/zaker/article_mongo.php?_appid=iphone&_bsize=640_1136&app_id=981&m=1454128094&pk=56ab005aa07aeca42f0006c8&style_v=2"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    __weak typeof(self) weakSelf = self;
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            weakSelf.zkModel=[ZKModel mj_objectWithKeyValues:responseObject];
            NSString *strContent=[NSString stringWithFormat:@"<html><head></head><body>%@</body></html>",self.zkModel.data.content];
            [weakSelf.webView loadHTMLString:strContent baseURL:[NSURL URLWithString:[[NSBundle mainBundle] resourcePath]]];
        }
    }];
    [dataTask resume];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [self loadImages];
}

-(void)loadImages{
    SDWebImageManager *manager=[SDWebImageManager sharedManager];
    SDImageCache *cache=[SDImageCache sharedImageCache];
    
    NSString *url =@"(function(){"
    "var img=document.getElementById(\"%@\");"
    "if(img != null){"
    "img.src=\"%@\";"
    "}"
    "})();";
    int index=0;
    for (Media *media in self.zkModel.data.media) {
        dispatch_time_t time=dispatch_time(DISPATCH_TIME_NOW,  (int64_t)(0.5f * NSEC_PER_SEC));
        dispatch_after(time, dispatch_get_main_queue(), ^{
            [manager downloadImageWithURL:[NSURL URLWithString:media.url] options:SDWebImageHighPriority progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                if(image && finished){
                    NSString *key=[cache defaultCachePathForKey:media.url];
                    NSString *imageID=[NSString stringWithFormat:@"id_image_%d",index];
                    NSString *js=[NSString stringWithFormat:url,imageID,key];
                    [self.webView stringByEvaluatingJavaScriptFromString:js];
                }
            }];
        });
        index++;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end